package com.wakaca.design.pattern.creational.singleton;

import java.io.Serializable;

/**
 * 饿汉式 - 单例
 * 如果资源浪费少的话，可以使用这种方式
 * Created by wakava
 */
public class HungrySingleton implements Serializable,Cloneable{

    private final static HungrySingleton hungrySingleton;

    static{
        hungrySingleton = new HungrySingleton();
    }

    /** 解决反射攻击破坏单例对象 */
    private HungrySingleton(){
        if(hungrySingleton != null){
            throw new RuntimeException("单例构造器禁止反射调用");
        }
    }
    public static HungrySingleton getInstance(){
        return hungrySingleton;
    }

    // 通过修改 clone 方法来解决序列化对单例对象的破坏
    private Object readResolve(){
        return hungrySingleton;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return getInstance();
    }

}
